"use strict"

var Router = require('koa-router');
var config = require('../../config/config.js');
var debug = require('debug')('router_orgnization');
var dao = require('../../dao/orgnization.js');
var ferror = require('../../common/app_utils.js').formatError;
var errInfo = require('../../common/err_info.js');

debug('router:' + config.http.baseUrl + '/v1/orgnization');
var router = new Router({
	prefix: config.http.baseUrl + '/v1/orgnization'
});

/*
{
"name":"root", 
"description":"总部",
"path":[]
}

{
"name":"root", 
"description":"总部->华东区->广东省->广州市->天河区",
"path":[root, zone_east_china, province_gd, city_gz, section_tianhe]
}
*/
router.post('/', function*() {
	// debug('add orgnization');
	var inParams = this.request.inParams;
	// check input TODO
	var result = yield dao.create(inParams);
	this.body = result;
});

/*create a tree, isRoot must be true
{
	"name": "xx",
	"description": "xx",
	"isRoot": "true", <==============
	"sub": [{
		"name": "xx",
		"description": "xx",
		"sub": [...]
	}, {
		"name": "xx",
		"description": "xx",
		"sub": [...]
	}]
}*/
router.post('/tree', function*() {
	var inParams = this.request.inParams;
	debug('add orgnization', inParams);
	// check input TODO
	var result = yield dao.createTree(inParams);
	this.body = result;
});

// add vendors
/*
{
	orgnization:xxid
	vendor:{set:[xxid,xxid]}
}

{
	orgnization:xxid
	vendor:{add:[xxid,xxid]}
}

{
	orgnization:xxid
	vendor:{remove:[xxid,xxid]}
}
*/
router.post('/vendors', function*() {
	var inParams = this.request.inParams;
	// check input TODO
	var result = yield dao.updateVendor(inParams);
	debug('update vendor', result);
	this.body = result;
});

// read by id
router.get('/id/:id', function*() {
	var inParams = this.request.inParams;
	// check input TODO
	var result = yield dao.readById(inParams.id);
	this.body = result;
});


router.get('/tree', function*() {
	var json = {
		userId: this.session.userId
	};
	var result = yield dao.readAsTree(json);
	this.body = result;
});

module.exports = router.routes();